<?php

namespace App\Http\Logic;

use App\Models\AdminUser;
use App\Models\OsanGroup;
use App\Models\OsanGroupMenu;
use App\Models\OsanGroupUser;
use App\Models\osanMenu;

class Admin extends Logic
{
    /**
     * 获取用户信息
     * @return array
     */
    public function info(int $uid = 0): array
    {
        $user = AdminUser::query()->select(["id", "nickname"])->find($uid);
        if ($uid < 1 || !$user) {
            return [];
        }
        return $user->toArray();
    }

    /**
     * 获取用户菜单信息
     * @return array
     */
    public function getUserMenu(int $uid = 0): array
    {
        $user = $this->info($uid);
        if ($uid < 1 || !$user) {
            return [];
        }
        // 获取用户分组信息
        $rows = OsanGroupUser::query()->select(['gid'])->where('uid', $uid)->get()->toArray();
        $gid = array_column($rows, 'gid');

        // 如果有超级管理员权限，就返回所有菜单, 默认角色1就是超级管理员
        if (in_array(1, $gid)) { // admin
            $menuTree = OsanMenu::getValidAllMenu();
        } else {
            $menuIds = OsanGroupMenu::getMid($gid);
            $menuTree = OsanMenu::getTree($menuIds);
        }

        return $menuTree;
    }

    /**
     * @return array
     */
    public function groupList($params): array
    {
        $data = ['list' => []];
        $query = OsanGroup::query();
        $data['total'] = $query->count();
        if ($data['total'] === 0) {
            return $data;
        }
        $list = $query->offset(($params['page'] - 1) * $params['size'])->limit($params['size'])
            ->get()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['uids'] = OsanGroupUser::getUid([$v['id']]);
            $list[$k]['mids'] = OsanGroupMenu::getMid([$v['id']]);
        }
        $data['list'] = $list;
        return $data;
    }

    /**
     * @return bool
     */
    public function setGroupUser(int $gid = 0, array $uid = []): bool
    {
        return OsanGroupUser::setGroupUser($gid, $uid);
    }

    /**
     * @return bool
     */
    public function setGroupMenu(int $gid = 0, array $mid = []): bool
    {
        return OsanGroupMenu::setGroupMenu($gid, $mid);
    }
}
